package zh.cgserver.core;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class HttpServleRequest {
      private Socket socket ;
     private String method;
     private String url;
     private String protocol;
     private Map<String,String> map = new HashMap<>();
    public HttpServleRequest(Socket socket)throws IOException{
        this.socket =socket;

        //解析获取方式
        parseRequestLine();
        //解析消息头
        parseHeaders();
        //解析消息正文
        parseContent();

    }
    public void parseRequestLine()throws IOException{
        String str = readLine();
        String[] arrays = str.split(" ");
        method = arrays[0];
        url = arrays[1];
        protocol = arrays[2];
        System.out.println("消息头:"+str);
        System.out.println("method:"+method);
        System.out.println("url:"+url);
        System.out.println("protocol:"+protocol);

    }
    public void parseHeaders()throws IOException{

        while (true){
            String line = readLine();
            if (line.isEmpty()){
                break;
            }
            String[] strings = line.split(": ");
            map.put(strings[0],strings[1]);
            System.out.println("消息头："+line);
        }
        System.out.println("map"+map);
    }
    public void parseContent(){

    }
    public String readLine() throws IOException {
        InputStream is = socket.getInputStream();
        char head ='a',tail = 'a';
        StringBuilder sb = new StringBuilder();

        while (true){
            tail =(char)is.read();
           if (head==13 && tail==10){
               break;
           }
           sb.append(tail);
           head = tail;
        }

        return sb.toString().trim();
    }

    public String getMethod() {
        return method;
    }

    public String getUrl() {
        return url;
    }

    public String getProtocol() {
        return protocol;
    }

    public String getMap(String key){
        return map.get(key);
    }
}
